<template>
  <el-dialog
    v-model="visible"
    :title="`模板详情 - ${templateData.template_name || ''}`"
    width="1200px"
    destroy-on-close
    :before-close="handleBeforeClose"
  >
    <div v-loading="loading" class="detail-container">
      <!-- 基础信息 -->
      <el-card class="detail-section-card">
        <template #header>
          <span class="section-title">基础信息</span>
        </template>
        <el-descriptions :column="2" border class="base-info-descriptions">
          <el-descriptions-item label="模板名称">{{
            templateData.template_name || "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="模板代码">
            <span class="monospace-text">{{
              templateData.template_code || "-"
            }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="版本号">{{
            templateData.version || "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag
              :type="templateData.is_active ? 'success' : 'info'"
              size="small"
            >
              {{ templateData.is_active ? "启用" : "禁用" }}
            </el-tag>
            <el-tag
              v-if="templateData.is_default"
              type="warning"
              size="small"
              style="margin-left: 8px"
            >
              默认模板
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="总分"
            >{{ templateData.total_score || 100 }}分</el-descriptions-item
          >
          <el-descriptions-item label="使用资产数">
            {{
              templateData.usage_count
                ? templateData.usage_count.toLocaleString()
                : "0"
            }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{
            templateData.created_at || "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="创建人">{{
            templateData.created_by || "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="最后修改">{{
            templateData.updated_at || "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="模板描述" :span="2">{{
            templateData.description || "-"
          }}</el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 维度配置详情 -->
      <el-card class="detail-section-card" v-if="dimensionList.length > 0">
        <template #header>
          <span class="section-title"
            >维度配置详情 (共{{ dimensionList.length }}个维度)</span
          >
        </template>
        <DynamicTable :columns="dimensionColumns" :data="dimensionList" />
      </el-card>

      <!-- 风险等级配置和使用统计 -->
      <el-row :gutter="16">
        <el-col :span="12">
          <el-card class="detail-section-card">
            <template #header>
              <span class="section-title">风险等级配置</span>
            </template>
            <div class="risk-levels">
              <div
                v-for="(level, index) in riskLevels"
                :key="index"
                class="risk-level-item"
              >
                <span
                  class="risk-indicator"
                  :class="getRiskClass(level.name)"
                ></span>
                <span class="risk-name">{{ level.label }}:</span>
                <span class="risk-range">{{ level.range }}</span>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card
            class="detail-section-card"
            v-if="usageStats || templateData.usage_stats"
          >
            <template #header>
              <span class="section-title">使用统计</span>
            </template>
            <div class="usage-stats">
              <div class="stats-title">
                风险分布 (共{{
                  (
                    usageStats?.total_assets ||
                    templateData.usage_stats?.total_assets ||
                    0
                  ).toLocaleString()
                }}个资产)
              </div>
              <div class="progress-container">
                <div
                  v-for="(item, index) in riskDistributionList"
                  :key="index"
                  class="progress-item"
                >
                  <div class="progress-label">
                    <span
                      class="risk-indicator"
                      :class="getRiskClass(item.level)"
                    ></span>
                    {{ item.label }}: {{ item.count }}个
                    <span v-if="item.percentage > 0" style="color: #86909c">
                      ({{ item.percentage }}%)
                    </span>
                  </div>
                  <el-progress
                    :percentage="item.percentage"
                    :stroke-width="8"
                    :stroke-color="getRiskColor(item.level)"
                  ></el-progress>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 详细统计信息 -->
      <el-card
        class="detail-section-card"
        v-if="usageStats && usageStats.score_stats"
      >
        <template #header>
          <span class="section-title">详细统计信息</span>
        </template>
        <el-row :gutter="16">
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-label">使用资产数</div>
              <div class="stat-value">
                {{ (usageStats.total_assets || 0).toLocaleString() }}
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-label">平均分</div>
              <div class="stat-value">
                {{ usageStats.score_stats?.avg?.toFixed(2) || "-" }}
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-label">最低分</div>
              <div class="stat-value">
                {{ usageStats.score_stats?.min || "-" }}
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-label">最高分</div>
              <div class="stat-value">
                {{ usageStats.score_stats?.max || "-" }}
              </div>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="16" style="margin-top: 16px">
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-label">中位数</div>
              <div class="stat-value">
                {{ usageStats.score_stats?.median || "-" }}
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-label">最近更新</div>
              <div class="stat-value-small">
                {{ usageStats.latest_update || "-" }}
              </div>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 分数分布 -->
      <el-card
        class="detail-section-card"
        v-if="usageStats && usageStats.score_distribution"
      >
        <template #header>
          <span class="section-title">分数分布</span>
        </template>
        <div class="score-distribution">
          <div
            v-for="(count, range) in usageStats.score_distribution"
            :key="range"
            class="score-range-item"
          >
            <div class="score-range-label">{{ range }}分</div>
            <div class="score-range-bar">
              <div
                class="score-range-fill"
                :style="{
                  width: `${getScoreRangePercentage(
                    count,
                    usageStats.total_assets
                  )}%`,
                }"
              ></div>
            </div>
            <div class="score-range-count">{{ count }}个</div>
          </div>
        </div>
      </el-card>
    </div>

    <template #footer>
      <el-button @click="handleCancel">关闭</el-button>
      <el-button
        type="primary"
        @click="handleValidate"
        :loading="validating"
        :disabled="!templateData.id"
      >
        验证配置
      </el-button>
      <!-- <el-button type="default" @click="emit('edit', templateData.id)"
        >编辑</el-button
      >
      <el-button type="default" @click="emit('copy', templateData.id)"
        >复制</el-button
      > -->
      <!-- <el-button
        :type="templateData.is_active ? 'warning' : 'success'"
        @click="
          templateData.is_active
            ? emit('disable', templateData.id)
            : emit('enable', templateData.id)
        "
      >
        {{ templateData.is_active ? "禁用" : "启用" }}
      </el-button> -->
      <!-- <el-button
        type="danger"
        @click="emit('delete', templateData.id)"
        :disabled="(templateData.usage_count || 0) > 0"
      >
        删除
      </el-button> -->
    </template>
  </el-dialog>

  <!-- 验证结果对话框 -->
  <el-dialog
    v-model="showValidationDialog"
    title="模板配置验证结果"
    width="700px"
    destroy-on-close
  >
    <div v-loading="validating" class="validation-result">
      <template v-if="validationResult">
        <!-- 验证状态 -->
        <div
          class="validation-status"
          :class="validationResult.is_valid ? 'valid' : 'invalid'"
        >
          <el-icon :size="24" style="margin-right: 8px">
            <CircleCheck v-if="validationResult.is_valid" />
            <CircleClose v-else />
          </el-icon>
          <span style="font-size: 16px; font-weight: 500">
            {{ validationResult.is_valid ? "配置有效" : "配置无效" }}
          </span>
        </div>

        <!-- 错误列表 -->
        <div v-if="validationResult.errors.length > 0" class="errors-section">
          <div class="section-title">
            <el-icon><WarningFilled /></el-icon>
            错误 ({{ validationResult.summary?.error_count || 0 }})
          </div>
          <ul class="error-list">
            <li v-for="(error, index) in validationResult.errors" :key="index">
              {{ error }}
            </li>
          </ul>
        </div>

        <!-- 警告列表 -->
        <div
          v-if="validationResult.warnings.length > 0"
          class="warnings-section"
        >
          <div class="section-title">
            <el-icon><InfoFilled /></el-icon>
            警告 ({{ validationResult.summary?.warning_count || 0 }})
          </div>
          <ul class="warning-list">
            <li
              v-for="(warning, index) in validationResult.warnings"
              :key="index"
            >
              {{ warning }}
            </li>
          </ul>
        </div>

        <!-- 汇总信息 -->
        <div v-if="validationResult.summary" class="summary-section">
          <div class="section-title">配置汇总</div>
          <el-descriptions :column="2" border size="small">
            <el-descriptions-item label="维度总数">
              {{ validationResult.summary.total_dimensions || 0 }}
            </el-descriptions-item>
            <el-descriptions-item label="维度总分">
              {{ validationResult.summary.total_dimension_score || 0 }}分
            </el-descriptions-item>
            <el-descriptions-item label="模板总分">
              {{ validationResult.summary.template_total_score || 100 }}分
            </el-descriptions-item>
            <el-descriptions-item label="使用资产数">
              {{ (validationResult.summary.usage_count || 0).toLocaleString() }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </template>
    </div>

    <template #footer>
      <el-button type="primary" @click="showValidationDialog = false"
        >确定</el-button
      >
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {
  ref,
  defineProps,
  defineEmits,
  watch,
  onMounted,
  computed,
  h,
} from "vue";
import {
  ElMessage,
  ElTag,
  ElIcon,
  ElDescriptions,
  ElDescriptionsItem,
  ElRow,
  ElCol,
} from "element-plus";
import {
  CircleCheck,
  CircleClose,
  WarningFilled,
  InfoFilled,
} from "@element-plus/icons-vue";
import { DynamicTable } from "@/components/DynamicTable";
import type { TableColumn } from "@/components/DynamicTable/types";
import {
  getTemplateDetail,
  validateTemplate,
  getTemplateUsageStats,
} from "../../../servers";

// 定义属性和事件
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  templateId: {
    type: [String, Number],
    default: "",
  },
});

const emit = defineEmits([
  "edit",
  "copy",
  "enable",
  "disable",
  "delete",
  "update:modelValue",
]);

// 响应式数据
const visible = ref(props.modelValue);
const loading = ref(false);
const templateData = ref<any>({});
const usageStats = ref<any>(null);
const validating = ref(false);
const showValidationDialog = ref(false);
const validationResult = ref<any>(null);

// 监听显示状态变化
watch(
  () => props.modelValue,
  (val) => {
    visible.value = val;
    if (val && props.templateId) {
      fetchTemplateDetail(props.templateId);
    }
  }
);

// 监听模板ID变化
watch(
  () => props.templateId,
  (id) => {
    if (id && visible.value) {
      fetchTemplateDetail(id);
    }
  }
);

// 页面初始化
onMounted(() => {
  if (props.templateId && visible.value) {
    fetchTemplateDetail(props.templateId);
  }
});

// 获取模板详情和使用统计
const fetchTemplateDetail = async (id: string | number) => {
  loading.value = true;
  try {
    // 同时调用详情和统计接口
    const [detailRes, statsRes] = await Promise.all([
      getTemplateDetail({ template_id: Number(id) }),
      getTemplateUsageStats({ template_id: Number(id) }).catch((err) => {
        // 统计接口失败不影响详情显示
        console.warn("获取使用统计失败:", err);
        return null;
      }),
    ]);

    templateData.value = detailRes.data || {};
    usageStats.value = statsRes?.data || null;

    // 如果统计接口返回了数据，使用统计数据覆盖详情中的 usage_stats
    if (usageStats.value) {
      templateData.value.usage_stats = usageStats.value;
    }
  } catch (error) {
    console.error("获取模板详情失败:", error);
    ElMessage.error("获取模板详情失败");
  } finally {
    loading.value = false;
  }
};

// 维度列表
const dimensionList = computed(() => {
  if (
    !templateData.value.dimensions ||
    !Array.isArray(templateData.value.dimensions)
  ) {
    return [];
  }

  // 按 display_order 排序
  return [...templateData.value.dimensions].sort((a, b) => {
    return (a.display_order || 0) - (b.display_order || 0);
  });
});

// 维度表格列配置
const dimensionColumns = computed<TableColumn[]>(() => [
  {
    label: "维度名称",
    prop: "dimension_name",
    width: 150,
    show: true,
  },
  {
    label: "维度代码",
    prop: "dimension_code",
    width: 150,
    show: true,
    render: (row) => {
      return h("span", { class: "monospace-text" }, row.dimension_code || "-");
    },
  },
  {
    label: "最大分值",
    prop: "max_score",
    width: 100,
    align: "right",
    show: true,
    render: (row) => {
      return h("span", `${row.max_score || 0}分`);
    },
  },
  {
    label: "权重",
    prop: "weight",
    width: 100,
    align: "right",
    show: true,
    render: (row) => {
      return h("span", `${(row.weight || 0).toFixed(1)}%`);
    },
  },
  {
    label: "启用状态",
    prop: "is_enabled",
    width: 100,
    show: true,
    render: (row) => {
      return h(
        ElTag,
        {
          type: row.is_enabled ? "success" : "info",
          size: "small",
        },
        row.is_enabled ? "启用" : "禁用"
      );
    },
  },
  {
    label: "计算类型",
    prop: "calculation_type",
    width: 120,
    show: true,
  },
  {
    label: "聚合模式",
    prop: "aggregation_mode",
    width: 120,
    show: true,
  },
  {
    label: "规则摘要",
    prop: "calculation_config",
    minWidth: 200,
    show: true,
    showOverflowTooltip: true,
    render: (row) => {
      if (
        !row.calculation_config ||
        typeof row.calculation_config !== "object"
      ) {
        return h("span", "无规则配置");
      }

      const config = row.calculation_config;
      const items = Object.keys(config).map((key) => {
        return `${key}: ${config[key]}分`;
      });

      return h("span", items.join(", "));
    },
  },
]);

// 风险等级配置
const riskLevels = computed(() => {
  const thresholds = templateData.value.risk_level_thresholds;
  if (!thresholds || typeof thresholds !== "object") {
    // 默认配置
    return [
      { name: "safe", label: "安全", range: "90-100分" },
      { name: "low", label: "低风险", range: "80-89分" },
      { name: "medium", label: "中等风险", range: "60-79分" },
      { name: "high", label: "高风险", range: "40-59分" },
      { name: "critical", label: "严重", range: "0-39分" },
    ];
  }

  // 从 risk_level_thresholds 对象解析
  const levels = [
    { name: "safe", label: "安全", threshold: thresholds.safe },
    { name: "low", label: "低风险", threshold: thresholds.low },
    { name: "medium", label: "中等风险", threshold: thresholds.medium },
    { name: "high", label: "高风险", threshold: thresholds.high },
    { name: "critical", label: "严重", threshold: thresholds.critical },
  ];

  // 计算分数范围
  return levels.map((level, index) => {
    const current = level.threshold || 0;
    const next = index > 0 ? levels[index - 1].threshold - 1 : 100;
    return {
      ...level,
      range: `${current}-${next}分`,
    };
  });
});

// 风险分布列表
const riskDistributionList = computed(() => {
  const stats = usageStats.value || templateData.value.usage_stats;
  if (!stats || !stats.risk_distribution) {
    return [];
  }

  const dist = stats.risk_distribution;
  const total = stats.total_assets || 0;

  const levels = [
    { level: "safe", label: "安全" },
    { level: "low", label: "低风险" },
    { level: "medium", label: "中等风险" },
    { level: "high", label: "高风险" },
    { level: "critical", label: "严重" },
  ];

  return levels.map((item) => {
    const count = dist[item.level] || 0;
    // 优先使用 risk_percentage，如果没有则计算
    const percentage =
      stats.risk_percentage?.[item.level] ||
      (total > 0 ? parseFloat(((count / total) * 100).toFixed(1)) : 0);
    return {
      ...item,
      count,
      percentage:
        typeof percentage === "number" ? percentage : parseFloat(percentage),
    };
  });
});

// 计算分数分布百分比
const getScoreRangePercentage = (count: number, total: number) => {
  if (!total || total === 0) return 0;
  return (count / total) * 100;
};

// 风险等级样式
const getRiskClass = (level: string) => {
  const classMap: Record<string, string> = {
    safe: "risk-indicator-safe",
    low: "risk-indicator-low",
    medium: "risk-indicator-medium",
    high: "risk-indicator-high",
    critical: "risk-indicator-critical",
  };
  return classMap[level] || "risk-indicator-default";
};

// 风险等级颜色
const getRiskColor = (level: string) => {
  const colorMap: Record<string, string> = {
    safe: "#165DFF",
    low: "#52C41A",
    medium: "#FAAD14",
    high: "#FA8C16",
    critical: "#FF4D4F",
  };
  return colorMap[level] || "#8C8C8C";
};

// 验证模板配置
const handleValidate = async () => {
  if (!templateData.value.id) {
    ElMessage.warning("模板ID不存在");
    return;
  }

  validating.value = true;
  showValidationDialog.value = true;
  validationResult.value = null;

  try {
    const { data } = await validateTemplate({
      template_id: templateData.value.id,
    });

    validationResult.value = data || {};

    // 根据验证结果显示提示
    if (data?.is_valid) {
      if (data.warnings && data.warnings.length > 0) {
        ElMessage.warning({
          message: "配置验证通过，但有警告信息",
          duration: 3000,
        });
      } else {
        ElMessage.success("配置验证通过，所有检查项均正常");
      }
    } else {
      ElMessage.error({
        message: `配置验证未通过，发现 ${
          data?.summary?.error_count || 0
        } 个错误`,
        duration: 4000,
      });
    }
  } catch (error: any) {
    console.error("验证模板配置失败:", error);
    ElMessage.error(error?.message || "验证模板配置失败，请稍后重试");
    showValidationDialog.value = false;
  } finally {
    validating.value = false;
  }
};

// 取消
const handleCancel = () => {
  emit("update:modelValue", false);
};

// 关闭前处理
const handleBeforeClose = () => {
  emit("update:modelValue", false);
  return true;
};
</script>

<style scoped lang="scss">
.detail-container {
  max-height: 70vh;
  overflow-y: auto;
  padding-right: 10px;
}

.detail-section-card {
  margin-bottom: 16px;
  border-radius: 6px;
  border: 1px solid #f0f0f0;
}

.section-title {
  font-weight: 500;
  color: #1d2129;
}

.monospace-text {
  font-family: monospace;
  background-color: #f5f5f5;
  padding: 2px 6px;
  border-radius: 3px;
  font-size: 13px;
}

::v-deep .base-info-descriptions {
  margin-top: 10px;

  ::v-deep .el-descriptions__item {
    padding: 12px 16px;
  }

  ::v-deep .el-descriptions__label {
    width: 120px;
    font-weight: 500;
  }
}

.risk-levels {
  padding: 10px 0;
}

.risk-level-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  line-height: 1.6;
}

.risk-indicator {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  display: inline-block;
  margin-right: 8px;
  flex-shrink: 0;
}

.risk-indicator-safe {
  background-color: #165dff;
}

.risk-indicator-low {
  background-color: #52c41a;
}

.risk-indicator-medium {
  background-color: #faad14;
}

.risk-indicator-high {
  background-color: #fa8c16;
}

.risk-indicator-critical {
  background-color: #ff4d4f;
}

.risk-indicator-default {
  background-color: #8c8c8c;
}

.risk-name {
  width: 100px;
  font-weight: 500;
}

.risk-range {
  flex: 1;
}

.usage-stats {
  padding: 10px 0;
}

.stats-title {
  font-weight: 500;
  margin-bottom: 15px;
  color: #1d2129;
}

.progress-container {
  padding-left: 5px;
}

.progress-item {
  margin-bottom: 15px;
}

.progress-label {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
  font-size: 13px;
}

/* 验证结果样式 */
.validation-result {
  padding: 10px 0;
}

.validation-status {
  display: flex;
  align-items: center;
  padding: 16px;
  margin-bottom: 20px;
  border-radius: 6px;
  border: 1px solid;
}

.validation-status.valid {
  background-color: #f6ffed;
  border-color: #b7eb8f;
  color: #52c41a;
}

.validation-status.invalid {
  background-color: #fff2e8;
  border-color: #ffbb96;
  color: #ff4d4f;
}

.errors-section,
.warnings-section,
.summary-section {
  margin-bottom: 20px;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 6px;
  font-weight: 500;
  font-size: 14px;
  margin-bottom: 12px;
  color: #1d2129;
}

.errors-section .section-title {
  color: #ff4d4f;
}

.warnings-section .section-title {
  color: #faad14;
}

.error-list,
.warning-list {
  margin: 0;
  padding-left: 20px;
  line-height: 1.8;
}

.error-list li {
  color: #ff4d4f;
  margin-bottom: 6px;
}

.warning-list li {
  color: #faad14;
  margin-bottom: 6px;
}

.summary-section {
  margin-top: 20px;
}

/* 详细统计信息样式 */
.stat-item {
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 6px;
  text-align: center;
}

.stat-label {
  font-size: 13px;
  color: #86909c;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #1d2129;
}

.stat-value-small {
  font-size: 14px;
  color: #1d2129;
  font-weight: 500;
}

/* 分数分布样式 */
.score-distribution {
  padding: 10px 0;
}

.score-range-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  gap: 12px;
}

.score-range-label {
  width: 80px;
  font-size: 13px;
  color: #1d2129;
  font-weight: 500;
  flex-shrink: 0;
}

.score-range-bar {
  flex: 1;
  height: 24px;
  background-color: #f0f0f0;
  border-radius: 4px;
  overflow: hidden;
  position: relative;
}

.score-range-fill {
  height: 100%;
  background: linear-gradient(90deg, #165dff 0%, #52c41a 100%);
  transition: width 0.3s ease;
  border-radius: 4px;
}

.score-range-count {
  width: 60px;
  text-align: right;
  font-size: 13px;
  color: #86909c;
  flex-shrink: 0;
}
</style>
